package com.eagle.view.activity;

import android.os.Bundle;
import android.os.Handler;
import android.text.TextUtils;
import android.view.KeyEvent;
import android.widget.EditText;

import com.eagle.EApplication;
import com.eagle.R;
import com.eagle.service.TrafficService_;
import com.eagle.support.constants.Constants;
import com.eagle.support.helper.AccountHelper;
import com.eagle.support.utils.SoftInputKeyboardUtils;
import com.eagle.support.utils.ToastUtils;
import com.eagle.support.utils.Utils;
import com.eagle.view.activity.base.BaseCallActivity;

import org.androidannotations.annotations.AfterViews;
import org.androidannotations.annotations.Click;
import org.androidannotations.annotations.EActivity;
import org.androidannotations.annotations.EditorAction;
import org.androidannotations.annotations.ViewById;

/**
 * Created by gc on 2016/12/24. 登录页面
 */
@EActivity(R.layout.activity_login)
public class LoginActivity extends BaseCallActivity implements AccountHelper.IUserStateListener {

    @ViewById(R.id.et_username)
    protected EditText mEtUsername;

    @ViewById(R.id.et_password)
    protected EditText mEtPassword;

    private boolean mLogged;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        initExplodeTransition();
        setDarkStatusIcon(true);
    }

    @Click(R.id.btn_login)
    public void onClick() {
        if (!mLogged) {
            String username = mEtUsername.getText().toString();
            String password = mEtPassword.getText().toString();

            if (TextUtils.isEmpty(username)) {
                ToastUtils.showToast(this, "账号不能为空", R.id.layout_parent);
                return;
            }

            String appKey = "10004";
            String appSecret = "b0863fbb251746cdaa33fe09568cd1ef";
            String appSource = "SDK3.0Demo";
            showLoading();
            SoftInputKeyboardUtils.hideSoftInput(mEtPassword);
            mAccountHelper.login(username, password, appKey, appSecret, appSource);
        } else {
            transitionTo(MainActivity_.intent(this).get());
        }
    }

    @Override
    public void onUserStateHandler(int state) {
        runOnUiThread(() -> {
            if (Constants.UserStatus.ONLINE == state) {
                new Handler().postDelayed(() -> {
                    dismissLoading();
                    mLogged = true;
                    String username = mEtUsername.getText().toString();
                    EApplication.getSharedPreferences().edit().putString(Constants.LOGIN_UID, username).commit();
                    setResult(RESULT_OK);
                    finishPage();
                }, 1500);
            }
        });
    }

    @EditorAction(R.id.et_password)
    protected void onAction() {
        onClick();
    }

    @Override
    public void onBackPressed() {
        super.onBackPressed();
        setResult(RESULT_CANCELED);
        finishPage();
    }
}
